package com.itboye.ihomebank.activity.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.NewDeviceLoginBean;
import com.itboye.ihomebank.bean.OpenIdBean;
import com.itboye.ihomebank.bean.PersonDataBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SavePersonData;
import com.itboye.ihomebank.util.controller.LoginController;
import com.itboye.ihomebank.util.controller.LoginedState;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;
import com.umeng.message.IUmengCallback;

import java.util.Observable;
import java.util.Observer;

/**
 * 登录
 * 
 */
public class LoginActivity extends BaseOtherActivity implements Observer  , CommonCallback ,View.OnClickListener {
	View v_statusbar;
	ImageView close_icon;// 返回图片
	TextView add_shap_title_tv;// 标题
	EditText login_pass;// 密码
	EditText login_username;// 账号
	RelativeLayout passwordRl,phoneRl;
	TextView login_ok;// 登录
	TextView login_forget;// 忘记密码
	TextView login_register;// 手机注册
	ImageView login_three;// 第三方登录
	PersonDataBean bean;
	private String phone;
	private String password;

	private Context context;
	private UserPresenter userPresenter;
	public static String LOGINEXIT = "com.itboye.ihomebank.exit";// 登录界面推出指令

	ToggleButton login_tb;// 密码可见

	private KeyPresenter keyPresenter;

	static int LoginRequstCode=10;

	@Override
	public void onClick(View v) {
		super.onClick(v);
		Intent intetn = null;
		switch (v.getId()) {
		case R.id.close_icon:// 返回
			finish();
			break;
		case R.id.login_ok:// 登录
			phone = login_username.getText().toString();
			password = login_pass.getText().toString();
			if (TextUtils.isEmpty(phone)) {
				ByAlert.alert("请输入手机号");
			} else if (TextUtils.isEmpty(password)) {
				ByAlert.alert("请输入密码");
			} else {
				showProgressDialog("登录中,请稍后", true);
				SPUtils.put(LoginActivity.this, null, SPContants.USERNAME,
						phone);
				SPUtils.put(LoginActivity.this, null, SPContants.PASSWORD,
						password);
				SPUtils.put(LoginActivity.this, null, SPContants.MOBILE_PASS,
						password);
				login();
			}

			break;
		case R.id.login_forget:// 忘记密码
//			intetn = new Intent(LoginActivity.this, PasswordActivityOne.class);
			intetn = new Intent(this,ForgetPasswordActivity.class);
			startActivity(intetn);
			break;
		case R.id.login_register:// 手机注册
//			intetn = new Intent(LoginActivity.this, RegisterActivityOne.class);
			intetn = new Intent(this,RegisterActivityNew.class);
			startActivity(intetn);
			break;
		case R.id.login_three:// 第三方登录

			break;
		case R.id.login_tb:// 密码可见
			if (login_tb.isChecked()) {
				login_pass
						.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
			} else {
				login_pass.setInputType(InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
			}

			break;
			case R.id.phoneRl:
			case R.id.login_username:
				Log.d("click==","true");
				resetEdettextFocus(login_username);
				break;
			case R.id.passwordRl:
            case R.id.login_pass:
            	Log.d("click==","true");
				resetEdettextFocus(login_pass);
				break;
		default:
			break;
		}

	}

	//让edittext 方便获取焦点（点击父类parentview 让edittext 获取焦点并弹出软键盘）

	public void resetEdettextFocus(EditText editText){
		editText.setFocusable(true);
		editText.setFocusableInTouchMode(true);
		editText.requestFocus();
		//打开软键盘
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editText,InputMethodManager.SHOW_FORCED); //强制显示键盘
//		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
	}
	/**
	 * 登录
	 */
	public void login() {
		userPresenter = new UserPresenter(this);
		userPresenter.login(phone, password);
	}

	BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LoginActivity.this.finish();
		};
	};

	protected void onDestroy() {
		super.onDestroy();
		 unregisterReceiver(emailBroadcastReceiver);
	}
	String uid="";
	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		try {
			closeProgressDialog();
		} catch (Exception e) {
		}
		if (entity != null) {
			if (!entity.getCode().equals(0)) {
				if (entity.getEventType() == UserPresenter.user_success) {
					bean = (PersonDataBean) entity.getData();
					if (bean != null) {
						uid=bean.getId();
						userPresenter.loginByNewDevice(uid, MyApplcation.device_token,"");
//						dealData();
					}
				} else if (entity.getEventType() == UserPresenter.user_fail) {
					ByAlert.alert(entity.getMsg());
				} else if (entity.getEventType() == UserPresenter.bindKeJiXia_success) {
					//ByAlert.alert(entity.getData());
				} else if (entity.getEventType() == UserPresenter.bindKeJiXia_fail) {
					//ByAlert.alert(entity.getData());
				} else if (entity.getEventType() == UserPresenter.openid_success) {
					//ByAlert.alert(entity.getData());
					OpenIdBean b= (OpenIdBean) entity.getData();
					SPUtils.put(this, null,SPContants.OPENID, b.getOpenid());
				} else if (entity.getEventType() == UserPresenter.openid_fail) {
					//ByAlert.alert(entity.getData());
				}else if (entity.getEventType() == KeyPresenter.isregSitri_success) {//判断是否注册了白马云锁
				//	ByAlert.alert(entity.getData());
					if (entity.getData().equals("0")){
						keyPresenter.regSitri(uid);//注册到后台
						SLock.getServices().register(uid, "itboye");//注册到白马云锁
					}
				}else if (entity.getEventType() == KeyPresenter.isregSitri_fail) {
//					ByAlert.alert(entity.getData());
				}else if (entity.getEventType() == KeyPresenter.regSitri_success) {
					//ByAlert.alert(entity.getData());
				}else if (entity.getEventType() == KeyPresenter.regSitri_fail) {
					//ByAlert.alert(entity.getData());
				}else if (entity.getEventType() == UserPresenter.devicelogin_success){//调用新设备登录验证接口
					if (((NewDeviceLoginBean)entity.getData()).isNeed_sms()){//是否需要验证新设备
						Intent intent = new Intent(LoginActivity.this, AddDeviceActivity.class);
						intent.putExtra("phone",phone);
						startActivityForResult(intent,LoginRequstCode);
					}else {
						dealData();
					}

				}else if (entity.getEventType() == UserPresenter.devicelogin_fail){

                       ByAlert.alert(entity.getMsg());
				}else if (entity.getEventType() == UserPresenter.deviceloginSms_success){


				}else if (entity.getEventType() == UserPresenter.deviceloginSms_fail){


				}
			}
		}
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_login;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub
	}

	private void dealData(){
		//登录成功后数据处理
		Log.d("uid=======",bean.getUid());
		SavePersonData.saveData(LoginActivity.this,bean);
		try {
			LoginActivity.this.finish();
		} catch (Exception e) {
			// TODO: handle exception
		}
		keyPresenter.onJudge(uid);	//判断是否注册了白马云锁
		userPresenter.getOpenId(bean.getUid());//获取科技侠openid
		LoginController.setLoginState(new LoginedState());
		//通知 弹框弹出
		sendBroadcast(new Intent("login_tankuang"));
		// 发送广播通知更改头像
		Intent intent2 = new Intent("changeavart");
		sendBroadcast(intent2);
	}
	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		setStatusBarHeight(v_statusbar);
		login_username.setText("");// 测试使用
		login_pass.setText("");

		phoneRl.setOnClickListener(this);
		login_username.setOnClickListener(this);
		passwordRl.setOnClickListener(this);
		login_pass.setOnClickListener(this);
		keyPresenter=new KeyPresenter(this);
		// 短信登录发送过来的广播
		IntentFilter filter1 = new IntentFilter(LOGINEXIT);
		registerReceiver(emailBroadcastReceiver, filter1);
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub
	};

	@Override
	public void onSuccess(ResultData resultData) {
		if (resultData.getId() == ID.REGISTER) {//白马锁注册成功之后登陆
			SLock.getServices().login(uid, "itboye");
		}
	}

	@Override
	public void onFailed(ResultError resultError) {

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==LoginActivity.LoginRequstCode&&resultCode==AddDeviceActivity.DeviceResultCode){
			int data1 = data.getIntExtra("data", 3);
			if (data1==0){
				dealData();
			}else {
				ByAlert.alert("登录失败");
			}
		}
	}
}
